<template>
	<view class="page-index tab-bar-page">
		<!-- <topBar :tabTitle="passWordStatus ? `${getLanguageText('当前', AppSetting.language)} 第${AppSetting.periodsNum}期` : getLanguageText('初始化验证', AppSetting.language)"/> -->
		<topBar />
		<web-view :src="src"></web-view>
	</view>
</template>

<script>
import { 
	appStorageInit, 
	getAppSetting, 
	setOrderList,
	getOrderSetting,
	storageInit
} from '../../utils/appStorage'
import {  getLanguageText } from '../../utils/language'

export default {
	data() {
		return {
			src: "http://103.146.141.213/?t=" + new Date().getTime(),
			passWord: '#a9Qd83y4@7H',
			passWordValue: '',
			passWordStatus: true,
			// 本项目已包含uni ui组件，组件文档 详见：
			uniHref: 'https://uniapp.dcloud.io/component/README?id=uniui',
			fontsize: 12,
			collapseValue: ['0'],
			AppSetting: {},
			OrderSetting: {},
			updataForm: {
				orderNum: '',
				quantity: ''
			},
			tableSorrt: 1, // 1： 正序，0：倒序
			tableData: [],
			tableDatas: [],
			orderId: '',
			printContent: ''
		}
	},
	onLoad() {
		let height = 0; //定义动态的高度变量
		let statusbar = 0; // 动态状态栏高度
		uni.getSystemInfo({ // 获取当前设备的具体信息
			success: (sysinfo) => {
				statusbar = sysinfo.statusBarHeight;
				height = sysinfo.windowHeight;
			}
		});
		let currentWebview = this.$scope.$getAppWebview(); //获取当前web-view
		setTimeout(function() {
			let wv = currentWebview.children()[0];
			wv.setStyle({ //设置web-view距离顶部的距离以及自己的高度，单位为px
				top: statusbar, //此处是距离顶部的高度，应该是你页面的头部
				height: height - statusbar, //webview的高度
			})
		}, 200); //如页面初始化调用需要写延迟
	},
	computed: {
		// 根据订单列表动态计算订单总金额
		orederAmount() {
			let data = 0
			for (let i = 0; i < this.tableData.length; i++) {
				let item = this.tableData[i]
				if (!item.del) {
					data += item.quantity * (item.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
				}
			}
			return data
		}
	},
	methods: {
		getLanguageText,
		// getOrderListFn() {
		// 	getOrderList(data => {
		// 		let list = JSON.parse(JSON.stringify(data))
		// 		this.tableData = this.tableSorrt ? list : list.reverse()
		// 	})
		// },
		formSubmit(e) {
			console.log(this.updataForm)
			let { orderNum, quantity } = this.updataForm
			if (!orderNum) {
				uni.showToast({title: "请先填写号码", icon: 'error'})
				return
			}
			// if (orderNum == '00') {
			// 	uni.showToast({title: "号码格式有误", icon: 'error'})
			// 	return
			// }
			if(!quantity) {
				uni.showToast({title: "请先填写节数", icon: 'error'})
				return
			}
			if (orderNum.length == 1 || orderNum.length == 3) {
				uni.showToast({title: "号码格式有误", icon: 'error'})
				return
			}
			if (
				this.OrderSetting.quantityMaxNum_1 &&
				orderNum.length == 4 &&
				parseInt(quantity) > parseInt(this.OrderSetting.quantityMaxNum_2)
			) {
				uni.showToast({title: "节数超出限制", icon: 'error'})
				return
			}
			if (
				this.OrderSetting.quantityMaxNum_1 &&
				orderNum.length == 2 &&
				parseInt(quantity) > parseInt(this.OrderSetting.quantityMaxNum_2)
			) {
				console.log('quantity*****',quantity,this.OrderSetting.quantityMaxNum_2)
				console.log(quantity > this.OrderSetting.quantityMaxNum_2)
				uni.showToast({title: "节数超出限制", icon: 'error'})
				return
			}
			if (quantity && orderNum) {
				// 判断是否有重复号码
				if (this.tableData.find(v => v.orderNum == orderNum)) {
					this.tableData.map(v => {
						if (v.orderNum == orderNum) v.quantity += parseInt(quantity)
						return v
					})
				} else {
					this.tableData.push({
						orderNum,
						quantity: parseInt(quantity),
						orderType: orderNum.length == 2 ? 1 : 2,
						updataTime: new Date().valueOf(),
						id: this.orderId
					})
				}
				this.updataForm = { orderNum: '', quantity: '' }
			}
		},

		tableInit() {
			this.orderId = this.AppSetting.orderPr + new Date().valueOf()
			this.tableData = []
		},

		formReset(e) {
			console.log('清空数据')
		},

		timestampToTime: (timestamp) => {
      // 时间戳为10位需*1000，时间戳为13位不需乘1000
      let date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h = date.getHours() + ":";
      let m = date.getMinutes() + ":";
      let s = date.getSeconds();
      return Y + M + D + h + m + s;
    },

		myClick(type, data) {
			switch (type) {
				case '密码验证':
					if(this.passWordValue == this.passWord) {
						this.passWordStatus = true
						uni.showToast({title: "验证通过", icon: 'success'})
						// 数据初始化
						storageInit()
					} else {
						uni.showToast({title: "密码错误", icon: 'error'})
					}
					break;
				case '订单详情':
					console.log(data)
					uni.navigateTo({
						url: '/pages/orderDetail/orderDetail?query=' + encodeURIComponent(JSON.stringify(data))
					})
					break;
				case '删除':
					uni.showModal({
						title: "确定删除数据？",
						// content: "（作废后数据无法恢复）",
						confirmText: "确定",
						confirmColor: "#007aff",
						cancelText: "取消",
						cancelColor: "#007aff",
						success: (res) => {
							if (res.confirm) {
								let del = true
								if (del) {
									// 硬删除
									this.tableData.splice(data.key, 1)
								} else {
									this.tableData = this.tableData.map(order => {
										if (order.id == data.id) order.del = 1
										return order
									})
								}
								uni.showToast({title: "删除成功", icon: 'success'})
							} else {
								console.log('取消')
							}
						}
					})
					break;
				case '立即下单':
					if (!this.tableData || !this.tableData.length) {
						uni.showToast({title: "请先填写数据", icon: 'error'})
						return
					}
					uni.showModal({
						title: "确定立即下单？",
						confirmText: "确定",
						confirmColor: "#007aff",
						cancelText: "取消",
						cancelColor: "#007aff",
						success: (res) => {
							if (res.confirm) {
								let order = {
									id: this.tableData[0].id,
									updataTime: this.tableData[0].updataTime,
									orderNumTwo: this.tableData.filter(v => v.orderType == 1).map(v => {
										return {
											orderNum: v.orderNum,
											quantity: v.quantity,
											orderType: v.orderType,
										}
									}),
									orderNumFour: this.tableData.filter(v => v.orderType == 2).map(v => {
										return {
											orderNum: v.orderNum,
											quantity: v.quantity,
											orderType: v.orderType,
										}
									}),
									orderNumListStr: this.tableData.map(v => {
										return `${v.orderNum}*${v.quantity}`
									})
								}
								// 号码维度
								setOrderList(this.tableData, () => {}, false, 'OrderList')
								// 订单维度
								setOrderList([order], () => {
									setTimeout(() => {
										uni.showToast({title: "下单成功", icon: 'success'})
										this.updataForm = { orderNum: '', quantity: '' }
										this.tableInit()
									}, 1000)
								}, false, 'OrderLists')
								let money = 0
								// 计算总金额
								for (let key = 0; key < this.tableData.length; key++) {
									const v = this.tableData[key];
									money += v.quantity * (v.orderNum.length == 4 ? this.OrderSetting.quantityPrice_1 : this.OrderSetting.quantityPrice_2)
								}
								this.printContent = `\r\n\r\n\r\n----------------------------\r\n\r\n\r\n订单编号：${order.id}\r\n\r\n下单号码: ${order.orderNumListStr.toString()}\r\n\r\n订单金额：￥${money}\r\n\r\n订单状态：未开奖\r\n\r\n订单下单时间：${this.timestampToTime(order.updataTime)}\r\n\r\n\r\n----------------------------\r\n\r\n\r\n`

								// console.log('打印内容----')
								console.log(this.printContent)
								this.$refs.bluetoothPrintingPopup.open()
								setTimeout(() => {
									this.$refs.bluetoothPrinting.blueadapterCheck()
								}, 500)
							}
						}
					})
					break;
				case '列表排序':
					this.tableSorrt = this.tableSorrt ? 0 : 1
					this.tableData.reverse()
					break;
				default:
					break;
			}
		},
	}
}
</script>

<style lang="scss">
	.page-index {
		color: #525252;
		.page-header {
			font-size: 0.8rem;
			color: #fff;
			padding: 0.6rem 0.5rem;
			background: linear-gradient(45deg,#409EFF, #007aff);
		}
		.table-tr {
			margin: 0.6rem 0 0;
			display: flex;
			align-items: center;
			border-top: 1px solid #f1f1f1;
			border-right: 1px solid #f1f1f1;
			background: #f1f1f1;
			.td {
				padding: 0.3rem 0.3rem;
				border-left: 1px solid #fefefe;
				font-size: 0.6rem;
				font-weight: bold;
			}
		}
		.table {
			margin: 0.2rem;
			height: 19rem
		}
		.uni-input, .uni-input-text {
			width: 15rem;
		}
	}
</style>
